package com.ma.a05;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.context.annotation.AnnotationBeanNameGenerator;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.support.GenericApplicationContext;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.core.io.Resource;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.core.type.classreading.CachingMetadataReaderFactory;
import org.springframework.core.type.classreading.MetadataReader;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @ClassName A05Application
 * @Author: mayongqiang
 * @DATE 2022/3/31 19:53
 * @Description: 常见工厂后处理器
 */

public class A05Application1 {
    private static final Logger log = LoggerFactory.getLogger(A05Application1.class);

    public static void main(String[] args) throws IOException {
        /* 一个干净的容器 */
        GenericApplicationContext context = new GenericApplicationContext();
        context.registerBean("config", Config.class);
        /* 1、非常典型的BeanFactory后处理器
        ConfigurationClassPostProcessor---> @ComponentScan @Bean @Import @ImportResource */
        //context.registerBean(ConfigurationClassPostProcessor.class);

        /* MapperScannerConfigurer --> mybatis @MapperScanner */
        //context.registerBean(MapperScannerConfigurer.class, bd -> {
        //    bd.getPropertyValues().add("basePackage", "com.ma.a05.mapper");
        //});

        /* 模拟工厂后处理器 进行组件扫描补充到BeanFactory
         * 1、通过AnnotationUtils工具类找到指定类上的@ComponentScan
         * 2、找@ComponentScan的basePackages，转换为路径，将路径下的类二进制文件读取进resource中
         * 3、分析每个资源的类名，是否带@Component注解及其派生注解
         * 4、如果有这两类注解，那么就更具类名生成对应的BeanDefinition 和 bean的名字
         * 5、根据[BeanName,BeanDefinition]注册进beanFactory中
         *  */
        ComponentScan componentScan = AnnotationUtils.findAnnotation(Config.class, ComponentScan.class);

        if (componentScan != null) {
            for (String basePackage : componentScan.basePackages()) {
                // com.ma.a05.component ---> classpath*:com.ma.a05.component/**/*.class
                String path = "classpath*:" + basePackage.replace(".", "/") + "/**/*.class";

                CachingMetadataReaderFactory factory = new CachingMetadataReaderFactory();
                AnnotationBeanNameGenerator generator = new AnnotationBeanNameGenerator();
                DefaultListableBeanFactory beanFactory = context.getDefaultListableBeanFactory();

                Resource[] resources = context.getResources(path);
                for (Resource resource : resources) {
                    MetadataReader reader = factory.getMetadataReader(resource);
                    //System.out.print("类名：   " + reader.getClassMetadata().getClassName());
                    AnnotationMetadata annotationMetadata = reader.getAnnotationMetadata();
                    //System.out.print("     是否加了@Component?   " + annotationMetadata.hasAnnotation(Component.class.getName()));
                    //System.out.println("     是否加了@Component派生注解?   " + annotationMetadata.hasMetaAnnotation(Component.class.getName()));

                    if (annotationMetadata.hasAnnotation(Component.class.getName())
                            || annotationMetadata.hasMetaAnnotation(Component.class.getName())) {
                        AbstractBeanDefinition bd = BeanDefinitionBuilder
                                .genericBeanDefinition(reader.getClassMetadata().getClassName())
                                .getBeanDefinition();
                        String beanName = generator.generateBeanName(bd, beanFactory);
                        beanFactory.registerBeanDefinition(beanName, bd);
                    }
                }
            }
        }

        context.refresh();
        for (String name : context.getBeanDefinitionNames()) {
            System.out.println(name);
        }


        context.close();
    }
}
